/**
 * Created by liuhaiming on 2016/01/19
 */
var editTable = {}

editTable.createEditDataTable = function (options) {
    var settings = {
        'tableId' : options.tableId,
        'columns' : options.columns,
        'hiddens' : options.hiddens,
        'formDataId' : options.formDataId,
        'beanName' : options.beanName,
        'ajax' : options.ajax,
        'editEnable':options.editEnable,
        editTransFunc : options.editTransFunc,
        aftEditFunc : options.aftEditFunc,
        saveTransFunc : options.saveTransFunc,
        aftAddLineFunc: options.aftAddLineFunc
    };

    var table = new EditDataTable(settings);
    table.init();

    return table;
}

function EditDataTable(optinos) {
    this.settings = optinos;
    this.table = null;
    this.currRow = null;

    this.init = function() {
        this.table = PubDataTable.init({
            "tableId" : this.settings.tableId,
            "serverSide" : false,
            // set the initial value
            paging:false,
            searching:false,
            ordering:false
        });

        if (this.settings.ajax != null) {
            var self = this;
            $.ajax({
                url: this.settings.ajax.url,
                data: this.settings.ajax.data,
                dataType: "json",
                async: true,
                type: "GET",
                success: function (result) {
                    var resultType = eval(result).result;
                    if (resultType == "success") {
                        if ( result.data != null ) {
                            for (var row = 0; row < result.data.length; row++) {
                                self.addLineByData(result.data[row]);
                            }
                        }
                    } else {
                        var tipMsg = "数据加载失败!";
                        var errMsg = eval(result).error_msg;
                        if(errMsg != null && errMsg != "") {
                            tipMsg += "\n" + errMsg;
                        }
                        alert(tipMsg);
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert("数据加载失败失败!");
                }
            });
        }
    };


    this.addLine = function() {
        if ( this.currRow ) {
            if ( !this.rowEmptyValid() ) {
                alert("编辑行内容为空，不允许切换！");
                return;
            }
            this.lineSave();
        }

        var value = [this.settings.columns.length];
        for (var colIdx = 0; colIdx < this.settings.columns.length; colIdx++) {
            value[colIdx] = "";
        }

        var newRow = this.table.fnAddData(value);
        var rowObj = this.table.fnGetNodes(newRow[0]);
        var self = this;
        $(rowObj).bind("click", function() {
            self.lineEdit(this);
        });

        this.lineEdit(rowObj);

        if (this.settings.aftAddLineFunc != null) {
            this.settings.aftAddLineFunc(this, rowObj);
        }
        $(rowObj).find("td").addClass("vertical-align: middle;");
    };

    this.delLine = function() {
        if (this.currRow == null) {
            alert("请选择要删除的行!");
            return;
        }

        if(window.confirm("确认是否删除此行？")){
            this.table.fnDeleteRow(this.currRow);
            this.currRow = null;

        }
    };

    this.lineEdit = function(rowObj) {
        if ( !this.settings.editEnable ) {
            this.currRow = rowObj;
            return;
        }

        if (this.currRow == rowObj) {
            return;
        }

        if (this.currRow) {
            if ( !this.rowEmptyValid(rowObj) ) {
                alert("编辑行内容为空，不允许切换！");
                return;
            }

            this.lineSave();
        }

        this.currRow = rowObj;
        var rowData = this.getSavedRowData(rowObj);

        var jqTds = $('>td', rowObj);

        var col;
        for ( var idx = 0; idx < this.settings.hiddens.length; idx++ ) {
            col = this.settings.hiddens[idx];
            $(rowObj).attr(col.key, rowData[col.key]);
        }

        for ( var idx = 0; idx < this.settings.columns.length; idx++ ) {
            col = this.settings.columns[idx];
            if ( col.enable ) {
                jqTds[idx].innerHTML = this.editTrans(col.key, col.type, rowData);
                if ( col.type == "Date" ) {
                    this.resetDatePicker(col.key);
                }

                if ( this.settings.aftEditFunc != null ) {
                    var self = this;
                    $("#" + col.key).bind("change", function() {
                        self.settings.aftEditFunc( self, this );
                    });
                }

            } else {
                var value = rowData[col.key];
                if ( col.type == "Double" ) {
                    value = commonUtils.fillDecimalZero(value);
                }

                $(this.currRow).find("td:eq(" + idx + ")").html( value );
            }
        }

        commonUtils.initInputMask();
    };

    this.resetDatePicker = function(name) {
        if (jQuery().datepicker) {
            $('#' + name).datepicker({
                rtl: Metronic.isRTL(),
                language: "cn",
                orientation: "top left",
                autoclose: true,
                format: "yyyy-mm-dd"
            });

            $('#' + name).parent('.input-group').bind('click', '.input-group-btn', function (e) {
                e.preventDefault();
                $('#' + name).datepicker('show');
            });
        }
    }

    this.editTrans = function(key, type, rowData) {
        if (this.settings.editTransFunc != null) {
            return this.settings.editTransFunc(key, type, rowData);
        } else {
            var valObj = this.getValue(key, type, rowData);
            return '<input id="' + key + '" name="' + key + '" type="text" class="form-control ' + valObj.mask + '" style="width:100%" value="' + valObj.val + '" />';
        }
    }

    this.getValue = function(key, type, rowData) {
        var valObj = {};
        valObj.val = rowData[key];
        valObj.mask = "";

        if ( "String" == type ) {
        } else if ( "Double" == type ) {
            valObj.mask = "mask_decimal";
            valObj.val = commonUtils.fillDecimalZero(valObj.val);
        } else {
            valObj.mask = "mask_number";
        }

        return valObj;
    }

    this.initInputMask = function () {
        var self = this;
        $(".mask_number").inputmask({
            rightAlignNumerics:false,
            digits: 0,
            integerDigits: 5
        });

        $(".mask_decimal").inputmask('decimal', {
            rightAlignNumerics:false,
            digits: 2,
            integerDigits: 5
        });
        $(".mask_decimal").bind("blur", function () {
            if ( $(this).val() != null && $(this).val().length > 0 ) {
                $(this).val( commonUtils.fillDecimalZero($(this).val()) );
            }

        });
    }

    this.lineSave = function() {
        if (this.currRow == null) {
            return;
        }

        var col;
        var rowData = this.getCurrRowData();
        for ( var idx = 0; idx < this.settings.hiddens.length; idx++ ) {
            col = this.settings.hiddens[idx];
            $(this.currRow).attr(col.key, rowData[col.key]);
        }

        for ( var idx = 0; idx < this.settings.columns.length; idx++ ) {
            col = this.settings.columns[idx];
            var value = rowData[col.key];
            if ( col.type == "Double" ) {
                value = commonUtils.fillDecimalZero(value);
            }

            $(this.currRow).attr(col.key, value);
            this.table.fnUpdate(value, this.currRow, idx, false);
        }

        this.table.fnDraw();
        this.currRow = null;
    };

    this.addLineByData = function(rowData) {
        this.addLine();

        var col;
        for ( var idx = 0; idx < this.settings.hiddens.length; idx++ ) {
            col = this.settings.hiddens[idx];
            $(this.currRow).attr(col.key, rowData[col.key]);
        }

        for ( var idx = 0; idx < this.settings.columns.length; idx++ ) {
            col = this.settings.columns[idx];
            var value = rowData[col.key];
            if ( col.type == "Double" ) {
                value = commonUtils.fillDecimalZero(value);
            } if ( col.type == "Date" ) {
                var reg = new RegExp("^[0-9]*$");
                if ( value != null && reg.test(value) ) {
                    var date = value instanceof Date ? value : new Date(value);
                    value = commonUtils.formatDate(date);
                }

            }

            $(this.currRow).attr(col.key, value);
            this.table.fnUpdate(value, this.currRow, idx, false);
        }

        this.table.fnDraw();
        this.currRow = null;
    };

    this.rowEmptyValid = function() {
        var rowData = this.getCurrRowData();

        var isNotEmply = false;
        var val = null;
        for ( var idx = 0; idx < this.settings.columns.length; idx++ ) {
            val = rowData[this.settings.columns[idx].key];
            if (val != null && val.length > 0) {
                isNotEmply = true;
                break;
            }
        }

        return isNotEmply;
    }

    this.getCurrRowData = function() {
        var rowData = {};

        var col;
        for ( var idx = 0; idx < this.settings.hiddens.length; idx++ ) {
            col = this.settings.hiddens[idx];
            rowData[col.key] = $(this.currRow).attr(col.key);
        }

        for ( var idx = 0; idx < this.settings.columns.length; idx++ ) {
            col = this.settings.columns[idx];
            if (col.setValue != null) {
                col.setValue(rowData);
            } else if ( !col.enable ) {
                rowData[col.key] = $(this.currRow).find("td:eq(" + idx + ")").html();
            } else {
                rowData[col.key] = $('#' + col.key, this.currRow).val();
            }
        }

        return rowData;
    }

    this.getSavedRowData = function(rowObj) {
        var tdClass = $(rowObj.firstChild).attr("class");
        if ( tdClass == "dataTables_empty" ) {
            return;
        }

        //var tableRowData = this.table.fnGetData(rowObj);
        var rowData = {};

        var col = null;
        for ( var idx = 0; idx < this.settings.hiddens.length; idx++ ) {
            col = this.settings.hiddens[idx];
            rowData[col.key] = $(rowObj).attr(col.key) ? $(rowObj).attr(col.key) : "";
        }

        for ( var idx = 0; idx < this.settings.columns.length; idx++ ) {
            col = this.settings.columns[idx];
            rowData[col.key] = $(rowObj).attr(col.key) ? $(rowObj).attr(col.key) : "";
        }

        return rowData;
    }

    this.initFormTableData = function() {
        this.lineSave();

        var cTable = $("#" + this.settings.tableId);
        var rows = cTable.find("tbody tr");
        var bodyData = $("#" + this.settings.formDataId);

        bodyData.empty();
        var rowIdx = 0;
        var rowData;

        // 构造表体行数据
        var self = this;
        $(rows).each(function() {
            rowData = self.getSavedRowData(this);
            if ( rowData != null ) {
                var col = null;
                for ( var idx = 0; idx < self.settings.hiddens.length; idx++ ) {
                    col = self.settings.hiddens[idx];
                    bodyData.append('<input type="hidden" name="' + self.settings.beanName + '[' + rowIdx + '].' + col.key + '" value="' + rowData[col.key] + '">');
                }

                for ( var idx = 0; idx < self.settings.columns.length; idx++ ) {
                    col = self.settings.columns[idx];
                    bodyData.append('<input type="hidden" name="' + self.settings.beanName + '[' + rowIdx + '].' + col.key + '" value="' + rowData[col.key] + '">');
                }
            }

            rowIdx++;
        });
    }

}